﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
using System.Diagnostics;

namespace Tema2_Adabd
{
    public partial class MainForm : Form
    {
        private void clkExport(object sender, EventArgs e)
        {
            if (cbExport.SelectedIndex == -1)
                return;
            if (txtFisierDest.Text == "")
            {
                MessageBox.Show("Nu ati un nume pentru fisierul de iesire.txt");
                return;
            }

            try
            {
                var item = this.cbExport.GetItemText(this.cbExport.SelectedItem);
                //MessageBox.Show(item);
                if (item == "PDF")
                {
                    exportToPDF();
                    return;
                }
                if (item == "Excel")
                {
                    exportToEXCEL();
                    return;
                }
                if (item == "CSV")
                {
                    exportToCSV();
                    return;
                }
                if (item == "HTML")
                {
                   // exportToHTML();
                    ExportDatatableToHtml();
                    return;
                }

                throw new Exception("Export invalid");
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString(), "Eroare");
            }
            finally
            {
                txtFisierDest.Text = "";
            }
        }

        public void writeCSV(DataGridView gridIn, string outputFile)
        {
            //test to see if the DataGridView has any rows
            if (gridIn.RowCount > 0)
            {
                string value = "";
                DataGridViewRow dr = new DataGridViewRow();
                StreamWriter swOut = new StreamWriter(outputFile);

                //write header rows to csv
                for (int i = 0; i <= gridIn.Columns.Count - 1; i++)
                {
                    if (i > 0)
                    {
                        swOut.Write(",");
                    }
                    swOut.Write(gridIn.Columns[i].HeaderText);
                }

                swOut.WriteLine();

                //write DataGridView rows to csv
                for (int j = 0; j <= gridIn.Rows.Count - 2; j++)
                {
                    if (j > 0)
                    {
                        swOut.WriteLine();
                    }

                    dr = gridIn.Rows[j];

                    for (int i = 0; i <= gridIn.Columns.Count - 2; i++)
                    {
                        if (i > 0)
                        {
                            swOut.Write(",");
                        }

                        if (dr.Cells[i].Value != null)
                            value = dr.Cells[i].Value.ToString();
                        else
                            break;
                        //replace comma's with spaces
                        value = value.Replace(',', ' ');
                        //replace embedded newlines with spaces
                        value = value.Replace(Environment.NewLine, " ");

                        swOut.Write(value);
                    }
                }
                swOut.Close();
            }

            MessageBox.Show("Export catre CSV realizat cu succes.");
        }

        private void exportToPDF()
        {
            try
            {
                dgProduse.DataSource = utilizator.toateProdusele();

                //Creating iTextSharp Table from the DataTable data
                PdfPTable pdfTable = new PdfPTable(dgProduse.ColumnCount);
                pdfTable.DefaultCell.Padding = 3;
                pdfTable.WidthPercentage = 30;
                pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfTable.DefaultCell.BorderWidth = 1;

                //Adding Header row
                foreach (DataGridViewColumn column in dgProduse.Columns)
                {
                    PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
                    cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
                    pdfTable.AddCell(cell);
                }

                //Adding DataRow
                foreach (DataGridViewRow row in dgProduse.Rows)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if (cell.Value == null)
                            break;
                        pdfTable.AddCell(cell.Value.ToString());
                    }
                }
                using (FileStream stream = new FileStream(txtFisierDest.Text, FileMode.Create))
                {
                    Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
                    PdfWriter.GetInstance(pdfDoc, stream);
                    pdfDoc.Open();
                    pdfDoc.Add(pdfTable);
                    pdfDoc.Close();
                    stream.Close();
                }

                MessageBox.Show("Export catre pdf realizat cu succes.");
            }
            catch (Exception exp)
            {
                MessageBox.Show("Eroare la exportul in pdf." + exp.ToString());
            }
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

        protected void ExportDatatableToHtml()
        {
            StringBuilder strHTMLBuilder = new StringBuilder();
            strHTMLBuilder.Append("<html >");
            strHTMLBuilder.Append("<head>");
            strHTMLBuilder.Append("</head>");
            strHTMLBuilder.Append("<body>");
            strHTMLBuilder.Append("<table border='1px' cellpadding='1' cellspacing='1' bgcolor='lightyellow' style='font-family:Garamond; font-size:smaller'>");

            strHTMLBuilder.Append("<tr >");
            try
            {
               dgProduse.DataSource = utilizator.toateProdusele();
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }

            int c = 0;
                foreach (DataGridViewColumn myColumn in dgProduse.Columns)
                {
                    strHTMLBuilder.Append("<td >");
                    strHTMLBuilder.Append(myColumn.Name);
                    strHTMLBuilder.Append("</td>");
                    c++;
                    if (c == 10)
                        break;

                }
                strHTMLBuilder.Append("</tr>");


                //foreach (DataGridViewRow myRow in dgProduse.Rows)
                //{

                //    strHTMLBuilder.Append("<tr >");
                //    int i = 0;
                //    foreach (DataGridViewColumn myColumn in dgProduse.Columns)
                //    {
                //        strHTMLBuilder.Append("<td >");
                //        strHTMLBuilder.Append(myRow.Cells[i++].Value.ToString());
                //        strHTMLBuilder.Append("</td>");

                //    }
                //    strHTMLBuilder.Append("</tr>");
                //}

                foreach (DataGridViewRow row in dgProduse.Rows)
                {
                    int i = 0;
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if (cell.Value != null)
                        {
                            strHTMLBuilder.Append("<td >");
                            strHTMLBuilder.Append(cell.Value.ToString());
                            strHTMLBuilder.Append("</td>");
                        }
                        i++;
                        if (i == 10)
                            break;
                    }
                    i = 0;

                    strHTMLBuilder.Append("</tr>");
                }

            strHTMLBuilder.Append("</table>");
            strHTMLBuilder.Append("</body>");
            strHTMLBuilder.Append("</html>");

            string Htmltext = strHTMLBuilder.ToString();

            System.IO.File.WriteAllText(@txtFisierDest.Text, Htmltext); 

            MessageBox.Show("Export catre html realizat cu succes.");
        }  

        private void exportToCSV()
        {
            if (txtFisierDest.Text == "")
            {
                MessageBox.Show("Nu ati completat campul corespunzator fisierului de iesire.");
                return;
            }
            try
            {
                dgProduse.DataSource = utilizator.toateProdusele();
                writeCSV(dgProduse, txtFisierDest.Text);
            }
            catch (Exception exp)
            {
                MessageBox.Show("Eroare la exportul in csv." + exp.ToString());
            }
        }

        private void exportToEXCEL()
        {
            try
            {
                dgProduse.DataSource = utilizator.toateProdusele();

                Excel.Application xlApp;
                Excel.Workbook xlWorkBook;
                Excel.Worksheet xlWorkSheet;
                object misValue = System.Reflection.Missing.Value;

                xlApp = new Excel.Application();
                xlWorkBook = xlApp.Workbooks.Add(misValue);
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                int i = 0;
                int j = 0;

                for (i = 0; i <= dgProduse.RowCount - 2; i++)
                {
                    for (j = 0; j <= dgProduse.ColumnCount - 2; j++)
                    {
                        if (j == 6)
                        {
                            //Imaginea nu o exportam catre excel.
                            continue;
                        }
                        DataGridViewCell cell = dgProduse[j, i];
                        xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
                    }
                }

                xlWorkBook.SaveAs(txtFisierDest.Text, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();

                releaseObject(xlWorkSheet);
                releaseObject(xlWorkBook);
                releaseObject(xlApp);

                MessageBox.Show("Export realizat cu succes.");
            }
            catch(Exception)
            {

            }
            //catch (Exception exp)
            //{
            //    MessageBox.Show("Eroare la exportul in excel." + exp.ToString());
            //}
        }
    }
}